<template>
  <div class="home">
    <div class="main-content">
      <!-- 左侧：朝代时间轴 -->
      <aside class="dynasty-aside">
        <h2 class="aside-title">朝代历程</h2>
        <el-scrollbar class="dynasty-scroll">
          <div
            v-for="dynasty in dynasties"
            :key="dynasty.dynastyId"
            class="dynasty-timeline-item"
            :class="{ active: selectedDynasty?.dynastyId === dynasty.dynastyId }"
            @click="selectDynasty(dynasty)"
          >
            <div class="timeline-dot"></div>
            <div class="timeline-content">
              <div class="dynasty-name">{{ dynasty.dynastyName }}</div>
              <div class="dynasty-years">{{ dynasty.startYear }} - {{ dynasty.endYear }}</div>
            </div>
          </div>
        </el-scrollbar>
      </aside>
      <!-- 中间：中国地图 -->
      <section class="map-section">
        <h2 class="section-title">中国陶瓷地图</h2>
        <div class="map-container">
          <v-chart
            v-if="mapLoaded"
            ref="chinaMap"
            :option="mapOption"
            autoresize
            style="width: 100%; height: 100%; min-height: 500px;"
            @click="onMapClick"
          />
        </div>
      </section>
      <!-- 右侧：详细信息卡片 -->
      <aside class="info-aside">
        <!-- 朝代信息卡片 -->
        <el-card class="info-card" v-if="selectedDynasty && !selectedRegion">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ selectedDynasty.dynastyName }}</span>
              <el-tag type="primary" size="small">朝代信息</el-tag>
            </div>
          </template>
          <div class="info-content">
            <div class="info-section">
              <span class="info-label">时间：</span>
              <span>{{ selectedDynasty.startYear }} - {{ selectedDynasty.endYear }}</span>
            </div>
            <div class="info-section">
              <span class="info-label">简介：</span>
              <span>{{ selectedDynasty.description || '暂无描述' }}</span>
            </div>
            <div class="info-section">
              <span class="info-label">瓷器特点：</span>
              <span>{{ selectedDynasty.ceramicFeatures || '暂无描述' }}</span>
            </div>
            <div class="info-section">
              <span class="info-label">代表窑口：</span>
              <span>{{ selectedDynasty.representativeKilns || '暂无描述' }}</span>
            </div>
            <div class="info-section">
              <span class="info-label">主要产区：</span>
              <div class="region-tags">
                <el-tag 
                  v-for="region in majorProvinces" 
                  :key="region"
                  type="success" 
                  size="small"
                  class="region-tag"
                >
                  {{ region }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="info-actions">
            <el-button type="primary" @click="viewLiterature">查看相关文献</el-button>
          </div>
        </el-card>

        <!-- 地区信息卡片 -->
        <el-card class="info-card" v-if="selectedRegion">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ selectedRegion.regionName }}</span>
              <el-tag type="success" size="small">地区信息</el-tag>
            </div>
          </template>
          <div class="info-content">
            <div class="info-section">
              <span class="info-label">历史概况：</span>
              <span>{{ selectedRegion.historySummary || '暂无描述' }}</span>
            </div>
            <div class="info-section">
              <span class="info-label">陶瓷特色：</span>
              <span>{{ selectedRegion.ceramicFeatures || '暂无描述' }}</span>
            </div>
            <div class="info-section">
              <span class="info-label">地理分区：</span>
              <span>{{ selectedRegion.geoArea || '暂无描述' }}</span>
            </div>
            
            <!-- 名窑信息 -->
            <div class="info-section" v-if="regionKilns.length > 0">
              <span class="info-label">名窑列表：</span>
              <div class="kiln-list">
                <div 
                  v-for="kiln in regionKilns" 
                  :key="kiln.kilnId"
                  class="kiln-item"
                >
                  <div class="kiln-name">{{ kiln.kilnName }}</div>
                  <div class="kiln-desc">{{ kiln.description || '暂无描述' }}</div>
                </div>
              </div>
            </div>
            <div class="info-section" v-else>
              <span class="info-label">名窑列表：</span>
              <span class="no-data">暂无窑口信息</span>
            </div>
          </div>
          <div class="info-actions">
            <el-button type="primary" @click="viewLiterature">查看相关文献</el-button>
            <el-button type="info" @click="clearSelection">返回朝代视图</el-button>
          </div>
        </el-card>

        <!-- 欢迎卡片 -->
        <el-card class="info-card empty-info" v-if="!selectedDynasty && !selectedRegion">
          <template #header>
            <div class="card-header">
              <span class="card-title">欢迎探索中国陶瓷文化</span>
            </div>
          </template>
          <div class="info-content">
            <div class="welcome-text">
              <p>请选择左侧朝代或点击地图省份查看详细信息</p>
              <p>探索中国陶瓷的千年历史与文化传承</p>
            </div>
          </div>
        </el-card>
      </aside>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, watch, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { dynastyApi } from '@/api/dynasty'
import { regionApi } from '@/api/region'
import { kilnApi } from '@/api/kiln'
import VChart from 'vue-echarts'
import * as echarts from 'echarts/core'
import { use } from 'echarts/core'
import { MapChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { TooltipComponent } from 'echarts/components'

use([MapChart, CanvasRenderer, TooltipComponent])

const router = useRouter()
const dynasties = ref([])
const regions = ref([])
const selectedDynasty = ref(null)
const selectedRegion = ref(null)
const regionKilns = ref([])
const loading = ref(false)
const chinaMap = ref(null)
const mapLoaded = ref(false)
const mapInstance = ref(null)

// 朝代-省份映射关系
const dynastyRegionMap = {
  '新石器时代': ['河南省', '陕西省', '山东省'],
  '夏商周': ['河南省', '陕西省', '山东省', '河北省'],
  '秦汉': ['陕西省', '江苏省', '河南省', '山东省'],
  '魏晋南北朝': ['浙江省', '江苏省', '河南省', '河北省'],
  '隋唐': ['浙江省', '江苏省', '河南省', '河北省', '陕西省'],
  '五代十国': ['浙江省', '江苏省', '河南省', '河北省', '陕西省'],
  '宋': ['江西省', '浙江省', '江苏省', '河南省', '河北省', '福建省'],
  '元': ['江西省', '浙江省', '江苏省', '河南省', '河北省', '福建省'],
  '明': ['江西省', '浙江省', '江苏省', '河南省', '河北省', '福建省', '广东省'],
  '清': ['江西省', '浙江省', '江苏省', '河南省', '河北省', '福建省', '广东省', '四川省'],
  '民国': ['江西省', '浙江省', '江苏省', '河南省', '河北省', '福建省', '广东省', '四川省'],
  '现代': ['江西省', '浙江省', '江苏省', '河南省', '河北省', '福建省', '广东省', '四川省', '湖南省', '重庆市']
}

// 计算当前朝代的主要省份
const majorProvinces = computed(() => {
  if (!selectedDynasty.value) return []
  return dynastyRegionMap[selectedDynasty.value.dynastyName] || []
})

// 基础地图配置
const baseMapOption = {
  backgroundColor: 'rgba(20,30,60,0.95)',
  tooltip: {
    trigger: 'item',
    formatter: '{b}<br/>点击查看详细信息'
  },
  series: [
    {
      type: 'map',
      map: 'china',
      roam: true,
      label: { show: false },
      data: [],
      selectedMode: false,
      itemStyle: {
        areaColor: '#e0e6f1',
        borderColor: '#3a4a6a'
      },
      emphasis: {
        itemStyle: {
          areaColor: '#a0cfff',
          borderColor: '#409eff',
          borderWidth: 2
        }
      }
    }
  ]
}

const mapOption = ref({ ...baseMapOption })

// 初始化地图，只注册一次
const initMap = async () => {
  try {
    if (!echarts.getMap('china')) {
      const res = await fetch('/china.json')
      const geoJson = await res.json()
      echarts.registerMap('china', geoJson)
    }
    mapLoaded.value = true
    // 注册后强制刷新option，确保渲染
    mapOption.value = { ...baseMapOption }
  } catch (error) {
    ElMessage.error('地图数据加载失败: ' + error.message)
  }
}

onMounted(async () => {
  await initMap()
  await nextTick()
  await fetchDynasties()
  await fetchRegions()
})

onBeforeUnmount(() => {
  // 清理地图实例
  if (mapInstance.value) {
    mapInstance.value.dispose()
  }
})

// 监听地图加载状态
watch(mapLoaded, (loaded) => {
  if (loaded) {
    console.log('地图加载状态变化:', loaded)
    // 延迟强制重新渲染地图
    setTimeout(() => {
      forceRenderMap()
    }, 200)
  }
})

// 监听地图组件引用
watch(chinaMap, (chart) => {
  if (chart && mapLoaded.value) {
    console.log('地图组件引用获取成功')
    mapInstance.value = chart
    // 延迟设置地图配置
    setTimeout(() => {
      forceRenderMap()
    }, 100)
  }
})

// 获取朝代数据
const fetchDynasties = async () => {
  try {
    loading.value = true
    const response = await dynastyApi.getAllDynasties()
    if (response.code === 0) {
      dynasties.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取朝代数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取地区数据
const fetchRegions = async () => {
  try {
    loading.value = true
    const response = await regionApi.getAllRegions()
    if (response.code === 0) {
      regions.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取地区数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取地区窑口数据
const fetchRegionKilns = async (regionId) => {
  try {
    const response = await kilnApi.getKilnsByRegion(regionId)
    if (response.code === 0) {
      regionKilns.value = response.data
    } else {
      regionKilns.value = []
    }
  } catch (error) {
    console.error('获取窑口数据失败:', error)
    regionKilns.value = []
  }
}

// 选择朝代
const selectDynasty = (dynasty) => {
  selectedDynasty.value = dynasty
  selectedRegion.value = null
  regionKilns.value = []
  
  // 高亮相关省份
  const provinces = majorProvinces.value
  console.log('选中朝代:', dynasty.dynastyName, '主要省份:', provinces)
  
  // 更新地图高亮
  updateMapHighlight(provinces)
}

// 选择地区
const selectRegion = async (region) => {
  selectedRegion.value = region
  selectedDynasty.value = null
  
  // 清除地图高亮
  updateMapHighlight()
  
  // 获取该地区的窑口信息
  await fetchRegionKilns(region.regionId)
}

// 清除选择
const clearSelection = () => {
  selectedDynasty.value = null
  selectedRegion.value = null
  regionKilns.value = []
  
  // 清除地图高亮
  updateMapHighlight()
}

// 查看文献
const viewLiterature = () => {
  const params = {}
  if (selectedDynasty.value) {
    params.dynastyId = selectedDynasty.value.dynastyId
  }
  if (selectedRegion.value) {
    params.regionId = selectedRegion.value.regionId
  }
  router.push({
    name: 'Literature',
    query: params
  })
}

// 地图点击事件
const onMapClick = async (params) => {
  if (!params.name) return
  
  const region = regions.value.find(r => r.regionName === params.name)
  if (region) {
    await selectRegion(region)
  }
}

// 更新地图高亮
const updateMapHighlight = (provinces = []) => {
  if (!mapLoaded.value) {
    console.log('地图未加载完成，跳过高亮更新')
    return
  }
  
  console.log('更新地图高亮，省份:', provinces)
  
  const newOption = {
    backgroundColor: 'rgba(20,30,60,0.95)',
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>点击查看详细信息'
    },
    series: [
      {
        type: 'map',
        map: 'china',
        roam: true,
        label: { show: false },
        data: provinces.map(name => ({
          name,
          value: 1,
          itemStyle: { 
            areaColor: '#ffd700', 
            borderColor: '#ff9800', 
            borderWidth: 2 
          }
        })),
        selectedMode: false,
        itemStyle: {
          areaColor: '#e0e6f1',
          borderColor: '#3a4a6a'
        },
        emphasis: {
          itemStyle: {
            areaColor: '#a0cfff',
            borderColor: '#409eff',
            borderWidth: 2
          }
        }
      }
    ]
  }
  
  mapOption.value = newOption
}

// 强制重新渲染地图
const forceRenderMap = () => {
  if (chinaMap.value && mapLoaded.value) {
    console.log('强制重新渲染地图')
    // 重新设置地图配置
    mapOption.value = {
      backgroundColor: 'rgba(20,30,60,0.95)',
      tooltip: {
        trigger: 'item',
        formatter: '{b}<br/>点击查看详细信息'
      },
      series: [
        {
          type: 'map',
          map: 'china',
          roam: true,
          label: { show: false },
          data: [],
          selectedMode: false,
          itemStyle: {
            areaColor: '#e0e6f1',
            borderColor: '#3a4a6a'
          },
          emphasis: {
            itemStyle: {
              areaColor: '#a0cfff',
              borderColor: '#409eff',
              borderWidth: 2
            }
          }
        }
      ]
    }
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  background: linear-gradient(135deg, #3a4a6a 0%, #1a223a 100%);
  padding: 0;
}
.main-content {
  display: flex;
  max-width: 1600px;
  margin: 0 auto;
  padding: 40px 20px;
  gap: 32px;
  min-height: 100vh;
}
.dynasty-aside {
  width: 280px;
  background: rgba(255,255,255,0.08);
  border-radius: 18px;
  padding: 24px 0;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  backdrop-filter: blur(10px);
}
.aside-title {
  color: #fff;
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 18px;
  letter-spacing: 2px;
}
.dynasty-scroll {
  width: 100%;
  height: 600px;
  padding: 0 16px;
}
.dynasty-timeline-item {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 10px;
  padding: 12px 16px;
  position: relative;
}
.dynasty-timeline-item:hover {
  background: rgba(64, 158, 255, 0.1);
  transform: translateX(5px);
}
.dynasty-timeline-item.active {
  background: linear-gradient(90deg, #409eff22 0%, #67c23a22 100%);
  box-shadow: 0 2px 8px rgba(255, 255, 255, 0.2);
  transform: translateX(5px);
}
.timeline-dot {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: #409eff;
  margin-right: 14px;
  border: 2px solid #fff;
  box-shadow: 0 0 0 2px #409eff44;
  transition: all 0.3s ease;
}
.dynasty-timeline-item.active .timeline-dot {
  background: #67c23a;
  box-shadow: 0 0 0 2px #67c23a44;
  transform: scale(1.2);
}
.timeline-content {
  display: flex;
  flex-direction: column;
}
.dynasty-name {
  color: #fff;
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 4px;
}
.dynasty-years {
  color: #b0c4de;
  font-size: 0.9rem;
}
.map-section {
  flex: 1;
  background: rgba(255,255,255,0.08);
  border-radius: 18px;
  padding: 24px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 700px;
  backdrop-filter: blur(10px);
}
.section-title {
  color: #fff;
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 18px;
  letter-spacing: 2px;
}
.map-container {
  width: 100%;
  height: 500px;
  background: #1a223a;
  border-radius: 14px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.2);
}
.info-aside {
  width: 380px;
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.info-card {
  background: rgba(255,255,255,0.12);
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.2);
  color: #fff;
  border: none;
  backdrop-filter: blur(10px);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-title {
  font-size: 1.3rem;
  font-weight: bold;
  color: #409eff;
}
.info-content {
  padding: 0;
}
.info-section {
  margin-bottom: 16px;
  color: #e0e6f1;
  font-size: 1rem;
  line-height: 1.6;
}
.info-label {
  color: #67c23a;
  font-weight: 500;
  margin-right: 8px;
  display: inline-block;
  min-width: 80px;
}
.region-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}
.region-tag {
  margin: 0;
}
.kiln-list {
  margin-top: 8px;
}
.kiln-item {
  background: rgba(255,255,255,0.05);
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
  border-left: 3px solid #409eff;
}
.kiln-name {
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}
.kiln-desc {
  color: #b0c4de;
  font-size: 0.9rem;
  line-height: 1.4;
}
.no-data {
  color: #909399;
  font-style: italic;
}
.info-actions {
  margin-top: 18px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
.welcome-text {
  text-align: center;
  color: #b0c4de;
  line-height: 1.8;
}
.empty-info {
  text-align: center;
  color: #b0c4de;
}
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
    align-items: center;
    gap: 18px;
    padding: 20px 10px;
  }
  .dynasty-aside, .info-aside {
    width: 90vw;
    min-width: 0;
    max-width: 98vw;
  }
  .map-section {
    min-width: 0;
    width: 98vw;
    padding: 12px;
  }
  .map-container {
    width: 98vw;
    height: 60vw;
    min-height: 300px;
    max-width: 700px;
  }
  .dynasty-scroll {
    height: 400px;
  }
}
@media (max-width: 768px) {
  .main-content {
    padding: 10px 5px;
  }
  .dynasty-aside {
    width: 95vw;
  }
  .map-section {
    width: 95vw;
  }
  .info-aside {
    width: 95vw;
  }
  .card-title {
    font-size: 1.1rem;
  }
  .info-section {
    font-size: 0.9rem;
  }
}
</style> 